/**
 * This file contains javascript to handle information of medicine.
 */
//////////////////////// LOADING A PAGE ////////////

function loadPage(sourceDiv, actionURL, medicineId) {        
    $.ajax ({     
    	type:		'POST',
        url:        actionURL + "?set_ajax_view",
        data:       "medicine_id=" + medicineId,      
        dataType:   "html",
        beforeSend: function() {                                          
            $('div#' + sourceDiv).hide("slow");         
        },
        complete:   function() {
            $('div#' + sourceDiv).show("slow");         
        },
        success:  function(data) {
            $("#" + sourceDiv).html(data);          
        }
    });
}

// Save medicine default usage.
function saveMedicineDefUsage() {
    var check = isReadyToSaveMedDefUsage();
    // Save medicine default usage
    if (check == false) {
        return;
    }
    var submitData = $('#add_med_def_usage_form').formSerialize();
    $.ajax ({
            type:   "POST",
            url:    "../Medicine/SaveMedicineDefUsageAjax?set_ajax_view",
            data:   submitData,
            beforeSend: function() {
                $('#btn_save').hide();
                $('#barLoading').show();                
            },
            complete:   function() {
                $('#btn_save').show();
                $('#barLoading').hide();
            },
            success:    function(data) {
                $('div#medicinePageContent').hide('slow');
                loadPage('medicineListContent', 'ListMedicineDefUsage', '');
                $('div#medicineListContent').show();
            }
    });
}

// Validation before saving medicine default usage.
function isReadyToSaveMedDefUsage() {
    ///////////////////// Validation /////////////////////
    /* 1. Check empty value */
    // check usage_title
    if (!isNotEmpty($('#usage_title'), _("Empty usage name"), "status_message")) {
        return false;
    }
    // check usage_num, usage_unit
    if (!isNotEmpty($('#usage_num'), _("Empty usage"), "status_message") &&
        !isNotEmpty($('#usage_unit'), _("Empty usage"), "status_message") ) {
        return false;
    }
    // check dosage
    if (!isNotEmpty($('#dosage'), _("Empty dosage"), "status_message")) {
        return false;
    }
    // check time
    if (!isNotEmpty($('#time'), _("Empty time"), "status_message")) {
        return false;
    }
    // check quantity
    if (!isNotEmpty($('#quantity_num'), _("Empty quantity"), "status_message") &&
        !isNotEmpty($('#quantity_title'), _("Empty quantity"), "status_message")) {
        return false;
    }
    /* 2. Check number */
    if (!checkNumber($('#usage_num'), _("Invalid usage"), "status_message", "#AAA")) {
        return false;
    }
    if (!checkNumber($('#dosage'), _("Invalid dosage"), "status_message", "#AAA")) {
        return false;
    }
    if (!checkNumber($('#time'), _("Invalid time"), "status_message", "#AAA")) {
        return false;
    }
    if (!checkNumber($('#quantity_num'), _("Invalid quantity"), "status_message", "#AAA")) {
        return false;
    }
    return true;
}

// Save medicine unit.
function saveMedicineUnit() {
    if (!isNotEmpty($('#unit_name'), _("Empty unit name"), "status_message")) {
        return;
    }
    var submitData = $('#add_med_unit_form').formSerialize();
    $.ajax ({
            type:   "POST",
            url:    "../Medicine/SaveMedicineUnitAjax?set_ajax_view",
            data:   submitData,
            beforeSend: function() {
                $('#btn_save').hide();
                $('#barLoading').show();                
            },
            complete:   function() {
                $('#btn_save').show();
                $('#barLoading').hide();
            },
            success:    function(data) {
                $('div#medicinePageContent').hide('slow');
                loadPage('medicineListContent', 'ListMedicineUnit', '');
                $('div#medicineListContent').show();
            }
    });
}

// Edit medicine default usage.
function editMedicineDefUsage(usageId) {
    $('#medicineListContent').hide();
    loadPage('medicinePageContent', 'EditMedicineDefUsage', usageId);
}

// Decorate the list of medicine unit with sort and paging function.
function decorateMedUnitList() {
    $('#medicine_unit_list')
        .tablesorter()
        .tablesorterPager({
                container: $("#pagination"),
                size: 40,
                positionFixed: false
        });
}

// Save medicine
function saveMedicine() {
	$('#successMessage1').text('');
	$('#status_message').text('');
    if (!isNotEmpty($('#medicine_name'), _("Empty medicine name"), "status_message")) {
        return;
    }        
    
    var submitData = $('#editMedicineForm').formSerialize();
    $.ajax ({
            type:   "POST",
            url:    "../Medicine/SaveMedicineAjax?set_ajax_view",
            data:   submitData,
            beforeSend: function() {
                $('#btn_save').hide();
                $('#barLoading').show();                
            },
            complete:   function() {
                $('#btn_save').show();
                $('#barLoading').hide();
            },
            success:    function(data) {
            	var data = parseInt(data);
                if (data == -1) {
                    $('#status_message').text(_('There is no default usage available for selected medicine usage and unit')).show();                    
                } else {	                
                	$('#successMessage1').text(_('Save successful')).show();
                }
            }
    });
}

function listMedicine() {
    $.ajax ({
    	type:		'POST',
        url:        "../Medicine/ListMedicineAjax?set_ajax_view",
        data:       "medicine_name=" + $('#medicine_name').val(),        			        
        beforeSend: function() {
            $('div#search_button').hide();
            $('div#search_button').next().show();                                               
        },
        complete:   function() {
            $('div#search_button').next().hide();
            $('div#search_button').show();
        },
        success:    function(data) {            
            fillTableData($('#medicine_list'), data);                                                                                     
            $('#medicine_container').show();     
        }
    });
}

//Fill data of 'medicine_list' table
function fillTableData(table, data) {
    $('tbody', table).children().remove();  
    $('tbody', table).append(data);
}

// Fill data of medicine_list's total
function fillTotalTableData(parentDiv, data) {
    $('table.total_table', parentDiv).remove();
    parentDiv.append(data);
    parentDiv.children('table:last-child').addClass('total_table');
}

//Edit medicine.
function editMedicine(medicineId) {    
    loadPage('medicinePageContent', '../Medicine/EditMedicine', medicineId);
}

function doSearch(event) {
	if (event.keyCode == 13){//ENTER
		listMedicine();
	}
}

function deleteMedicine(medicineId) {
	message = _('Delete medicine') + ' <b>' + $('#medicine_name_' + medicineId).html() + ' </b>?';
	
	promptConfirm(_("Delete"), message, function() {		
		
		$.ajax({
			type: 	'POST',	
			url:	'../Medicine/DeleteMedicine?set_ajax_view',
			data:	'medicineId=' + medicineId,
			success: function(data) {
				$('tr#' + medicineId).remove();
			}
		});
		return true;
	},'YesNo','warn',_('No'));	
}

function resetMedicineUsageForm() {
	$('#status_message').text('').hide();
	$('#hid_id').val('');
	$('form#form_medicine_usage input:text').val('').css('border-color', '#AAA');	
}

function editMedicineUsage( id, usage_title, usage_num, usage_unit,  
		dosage, time, quantity_num, quantity_title) {
	
	//Reset form before show
	resetMedicineUsageForm();
	
	//Set value
	$('#hid_id').val(id);
	$('#usage_title').val(usage_title);	
	$('#usage_num').val(usage_num);
	$('#usage_unit').val(usage_unit);
	$('#dosage').val(dosage);
	$('#time').val(time);
	$('#quantity_num').val(quantity_num);
	$('#quantity_title').val(quantity_title);	
	//Show form
	$('#div_medicine_usage').show();
	
}

function cancelMedicineUsage() {
	resetMedicineUsageForm();
	$('#div_medicine_usage').hide();
	
}

function saveMedicineUsage() {
	// Validate
	if ( !validateMedicineUsageForm() ) {
		return;
		
	}
	
	var submitData = $('#form_medicine_usage').formSerialize();
	
	$.ajax({
		type: 'POST',
		url: '../Medicine/saveMedicineUsageAjax?set_ajax_view',
		data: submitData,
		beforeSend: function() {
			$('form#form_medicine_usage input:button').hide();
			$('#barLoading').show();
		
		},
		complete: function() {
			$('form#form_medicine_usage input:button').show();
			$('#barLoading').hide();
			
		},
		success: function(data) {			
			loadPage('medicineListContent', 'ListMedicineDefUsage', '');
			
		}
		
	});

}

function validateMedicineUsageForm() {
	if ( $.trim( $('#usage_title').val() ) == '' ) {
		$('#status_message').text(_('Not yet input usage name')).show();
		$('#usage_title').css('border-color', 'red').focus();
		
		return false;
		
	}
	
	return true;
	
}

// Decorate the list of medicine default usage with sort and paging function.
function decorateMedicineDefUsageList() {
    $('#medicine_def_usage_list')
        .tablesorter()
        .tablesorterPager({
                container: $("#pagination"),
                size: 40,
                positionFixed: false
        });
}














